package cn.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * mapping测试,包含如下内容
 * 1) RequestMapping的Get和Post测试
 * 2) GetMapping
 * 3) PostMapping
 * 4) DeleteMapping
 * 5) PathVariable
 * <p>
 * 测试工具:PostMan,因为有post、delete等请求,浏览器只能发送get故需要该工具模拟
 */
@Controller
@RequestMapping("mapping")
public class MappingController {

    @RequestMapping("req/get")
    public String testRequestGet(HttpServletRequest request, HttpServletResponse response, Model model) {
        model.addAttribute("msg", "这是 RequestMapping Get 请求");
        return "mapping"; // 已经在springmvc.xml中配置视图解析器,可省略前后缀
        /**
         * 访问 http://localhost:8080/mapping/req/get
         * 网页显示 "这是 RequestMapping Get 请求"
         */
    }

    @RequestMapping("req/post")
    @ResponseBody
    public String testRequestPost() {
//        return "这是 RequestMapping Post 请求";
        return "This is requestMapping-post request";
        /**
         * 因为默认返回是视图,故使用 @ResponseBody 注解改为json串
         * postman中文测试存在乱码问题,暂时先不解决该问题,故返回值中改为没有中文字符
         *
         * 因为 @RequestMapping 注解 Get 和 Post 均能响应,故分别进行测试
         * 1) Get 请求(浏览器或者postman均可)
         * http://localhost:8080/mapping/req/post
         * 页面显示 "This is requestMapping-post request"
         *
         * 2) Post 请求 (postman中将请求类型改为post)
         * http://localhost:8080/mapping/req/post
         * 页面显示 "This is requestMapping-post request"
         */
    }

    @GetMapping("get")
    public String testGet(HttpServletRequest request, HttpServletResponse response, Model model) {
        model.addAttribute("msg", "这是 GetMapping 请求");
        return "mapping";
        /**
         * 访问 http://localhost:8080/mapping/get
         * 网页显示 "这是 GetMapping 请求"
         */
    }

    @PostMapping("post")
    @ResponseBody
    public String testPost(HttpServletRequest request, HttpServletResponse response, Model model) {
//        return "这是 PostMapping 请求";
        return "This is postMapping request";
        /**
         * postman 改为post请求方式,然后访问
         * http://localhost:8080/mapping/post
         * 页面内容 "This is postMapping request"
         */
    }

    @DeleteMapping("delete")
    @ResponseBody
    public String testDelete() {
//        return "这是 DeleteMapping 请求";
        return "This is DeleteMapping request";
        /**
         * postman 改为delete请求方式,然后访问
         * http://localhost:8080/mapping/delete
         * 页面内容 "This is DeleteMapping request"
         */
    }

    @RequestMapping("info/{uid}")
    public String testPathVariable(@PathVariable("uid") String id, Model model) {
        model.addAttribute("msg", "这是 PathVariable Restful 请求, uid = " + id);
        return "mapping";
        /**
         * 访问 http://localhost:8080/mapping/info/10
         * 网页显示 "这是 PathVariable Restful 请求, uid = 10"
         */
    }
}
